﻿using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace DeHeng_Mes.Utils
{
    public class HttpResult
    {
        public HttpStatusCode StatusCode { get; set; }
        public string ResponseJson { get; set; }
        public bool IsSuccess { get; set; }
        public string ErrorMessage { get; set; }
    }

    public static class ApiUtil
    {
        private static readonly HttpClient _httpClient = new HttpClient();

        public static async Task<HttpResult> SendJsonRequestAsync(
            string url,
            object requestData,
            HttpMethod method = null,
            string authToken = null)
        {
            var result = new HttpResult();

            try
            {
                using (var requestMessage = new HttpRequestMessage(method ?? HttpMethod.Post, url))
                {
                    // 添加认证头
                    if (!string.IsNullOrEmpty(authToken))
                    {
                        requestMessage.Headers.Authorization =
                            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authToken);
                    }

                    // 序列化请求数据
                    if (requestData != null)
                    {
                        var jsonContent = JsonSerializer.Serialize(requestData);
                        requestMessage.Content = new StringContent(
                            jsonContent,
                            Encoding.UTF8,
                            "application/json");
                    }

                    // 发送请求
                    var response = await _httpClient.SendAsync(requestMessage);

                    // 记录状态码
                    result.StatusCode = response.StatusCode;
                    result.IsSuccess = response.IsSuccessStatusCode;

                    // 读取响应内容
                    result.ResponseJson = await response.Content.ReadAsStringAsync();

                    if (!response.IsSuccessStatusCode)
                    {
                        result.ErrorMessage = $"HTTP Error: {(int)response.StatusCode} {response.StatusCode}";
                    }
                }
                ;
            }
            catch (HttpRequestException ex)
            {
                result.ErrorMessage = $"Request Error: {ex.Message}";
                result.IsSuccess = false;
            }
            catch (Exception ex)
            {
                result.ErrorMessage = $"Unexpected Error: {ex.Message}";
                result.IsSuccess = false;
            }

            return result;
        }
    }
}
